import json
import hashlib
import os
from pathlib import Path

# 默认用户文件路径
DEFAULT_USERS_FILE = 'users.json'

def get_users_file_path():
    """获取用户文件路径"""
    import configparser
    config = configparser.ConfigParser()
    config.read('../config/config.ini')
    return config.get('auth', 'users_file', fallback=DEFAULT_USERS_FILE)

def hash_password(password):
    """对密码进行哈希处理"""
    return hashlib.sha256(password.encode('utf-8')).hexdigest()

def create_user(username, password):
    """创建新用户"""
    users_file = get_users_file_path()
    users = load_users()
    users[username] = hash_password(password)
    
    # 确保目录存在
    Path(os.path.dirname(users_file)).mkdir(parents=True, exist_ok=True)
    
    with open(users_file, 'w') as f:
        json.dump(users, f)

def load_users():
    """加载用户数据"""
    users_file = get_users_file_path()
    try:
        if os.path.exists(users_file):
            with open(users_file, 'r') as f:
                return json.load(f)
    except Exception:
        pass
    return {}

def authenticate(username, password):
    """验证用户身份"""
    users = load_users()
    stored_hash = users.get(username)
    if stored_hash and stored_hash == hash_password(password):
        return True
    return False

# 创建示例用户
if __name__ == "__main__":
    create_user("admin", "admin123")
    create_user("user", "user123")    
